import React, { Component } from 'react';
import { Button, StyleSheet, Text, View, StatusBar } from 'react-native';
import Geolocation from './../../js/geolocation';

export default class GeolocationPage extends Component {
  state = { location: {} };

  async componentDidMount() {
    await Geolocation.init();
    Geolocation.setOptions({
      interval: 10000,
      distanceFilter: 10,
      background: true,
      reGeocode: true
    });
    Geolocation.addLocationListener(location =>
      this.updateLocationState(location)
    );
    Geolocation.createFence();
  }

  componentWillUnmount() {
    Geolocation.stop();
    Geolocation.removeFence();
  }

  updateLocationState(location) {
    if (location) {
      location.timestamp = new Date(location.timestamp).toLocaleString();
      this.setState({ location });
    }
  }

  startLocation = () => Geolocation.start();
  stopLocation = () => Geolocation.stop();
  getLastLocation = async () =>
    this.updateLocationState(await Geolocation.getLastLocation());

  render() {
    const { location } = this.state;
    return (
      <View style={style.body}>
        <StatusBar
          translucent
          hidden={false}
          barStyle="dark-content"
          backgroundColor="transparent"
        />
        <View style={style.controls}>
          <Button
            style={style.button}
            onPress={this.startLocation}
            title="开始定位"
          />
          <Button
            style={style.button}
            onPress={this.stopLocation}
            title="停止定位"
          />
        </View>
        {Object.keys(location).map(key => (
          <View style={style.item} key={key}>
            <Text style={style.label}>{key}</Text>
            <Text>{location[key]}</Text>
          </View>
        ))}
      </View>
    );
  }
}

const style = StyleSheet.create({
  body: {
    padding: 16,
    paddingTop: StatusBar.currentHeight
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 12,
    marginBottom: 24
  },
  item: {
    flexDirection: 'row',
    marginBottom: 4
  },
  label: {
    color: '#f5533d',
    width: 120,
    paddingRight: 10,
    textAlign: 'right'
  }
});
